package com.sgzn.sgpay.service.tcp;


import com.sgzn.sgpay.service.SgsCreditIncreaseCallBackService;
import com.sgzn.sgpay.service.SgsDeviceService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
import java.util.Timer;

/**
 * Created by xxjs-gd-llf
 * DATETIME:2018/4/11 13:46
 * Description:
 */
@Slf4j
public class SgTcpServer {
    private static final int SERVER_PORT = 3000;
    public static final int HEARTBEATCOUNT_INTERVAL=3;
    public static final int HEARTBEAT_TIMEOUT=500;//1500S

    public static Map<String,Socket> socketList = Collections.synchronizedMap(new HashMap<String,Socket>());
    public static Map<String,String> registerCodeMap =Collections.synchronizedMap(new HashMap<String,String>());
    public static Map<String,Integer> heartBeatCountMap = Collections.synchronizedMap(new HashMap<String, Integer>());

    public static ApplicationContext applicationContext;
    public static SgsCreditIncreaseCallBackService sgsCreditIncreaseCallBackService;
    public static SgsDeviceService sgsDeviceService;

    static {
        if (applicationContext == null) {
                applicationContext = new ClassPathXmlApplicationContext(new String[] { "applicationContext-service.xml" });
        }
        sgsCreditIncreaseCallBackService = (SgsCreditIncreaseCallBackService) applicationContext.getBean("sgsCreditIncreaseCallBackServiceImpl");
        sgsDeviceService = (SgsDeviceService)applicationContext.getBean("sgsDeviceServiceImpl");
    }

    public void init(){
        try {
            final ServerSocket serverSocket = new ServerSocket(SERVER_PORT);
            //起一个主线程专门监听--监听线程
            new Thread(new Runnable() {
                @Override
                public void run() {
                    while (true){
                        try {
                            log.info("监听请求.....");
                            Socket socket = serverSocket.accept();
                            new SgsTcpListenService(socket).start(); //接受到一个连接后起一个工作线程来处理连接
                        }catch (IOException e){
                            e.printStackTrace();
                        }
                    }
                }
            }).start();

            //起一个定时任务心跳线程，专门用来计数心跳信息 3秒后启动，每隔3秒起来一次
            Timer timer = new Timer();
            timer.schedule( new SgTcpMonitorHeartBeartCountTask(),HEARTBEATCOUNT_INTERVAL*1000,HEARTBEATCOUNT_INTERVAL*1000);


        }catch ( IOException e){
                e.printStackTrace();

        }
    }


    public static void main(String[]  args ){
        SgTcpServer sgTcpServer = new SgTcpServer();
        sgTcpServer.init();

    }
}
